﻿using FinalPointSet.Model.Asset;
using ICSharpCode.AvalonEdit.Highlighting;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;

namespace FinalPointSet.Model.Model.Knowledge
{
    /// <summary>
    /// 语言高亮配置
    /// </summary>
    public class HighLight
    {
        /// <summary>
        /// 名称
        /// </summary>
        public string Name { get; set; } = string.Empty;
        /// <summary>
        /// 代码高亮
        /// </summary>
        public IHighlightingDefinition? HighlightingDefinition { get; set; }
        public HighLight() { }

        public HighLight(string name)
        {
            Name = name;
        }

        public HighLight(string name, IHighlightingDefinition? highlightingDefinition) : this(name)
        {
            HighlightingDefinition = highlightingDefinition;
        }

        public static HighLight Copy(HighLight highLight)
        {
            return new HighLight(highLight.Name, highLight.HighlightingDefinition);
        }
        /// <summary>
        /// 代码高亮的序列化器
        /// </summary>
        public class HighLightConverter : JsonConverter<HighLight>
        {
            /// <summary>
            /// 代码高亮集合
            /// </summary>
            private readonly List<ObjectPair<IHighlightingDefinition>> highLights = [];
            public HighLightConverter() { }
            public HighLightConverter(List<ObjectPair<IHighlightingDefinition>> highLights)
            {
                this.highLights = highLights;
            }
            public override void WriteJson(JsonWriter writer, HighLight? value, JsonSerializer serializer)
            {
                ArgumentNullException.ThrowIfNull(value);
                //只序列化Name属性
                JObject obj = new()
            {
                { "Name", value.Name }
            };
                obj.WriteTo(writer);
            }
            public override HighLight? ReadJson(JsonReader reader, Type objectType, HighLight? existingValue, bool hasExistingValue, JsonSerializer serializer)
            {
                var jsonObj = JObject.Load(reader);
                HighLight result = new();
                // 反序列化单独的属性
                if (jsonObj["Name"] is JToken jtName)
                    result.Name = jtName.ToString();

                // 反序列化代码高亮
                if (highLights != null && highLights.Count > 0)
                {
                    ObjectPair<IHighlightingDefinition>? pair = highLights.Find(e => e.Name.Equals(result.Name, StringComparison.OrdinalIgnoreCase));
                    result.HighlightingDefinition = pair?.Value;
                }

                return result;
            }
        }

    }
}
